<?php 

namespace app\recordpen\controller;

use app\recordpen\controller\FileTagCore;

class FileTagLogic {
	/**
	 * 创建重点标注 - Logic
	 */
	public static function createFileTagLogic($fid, $tag) {
		// 验证重点标注是否存在
		$res = FileTagCore::verifyFileTagIsExist($fid);
		if ($res->isSuccess) { return $res; }

		// 创建标注
		$res = FileTagCore::createFileTagCore($fid, $tag);
		return $res;
	}

	/**
	 * 获取重点标注 - Logic
	 */
	public static function getFileTagLogic($fid) {
		// 验证重点标注是否存在
		$res = FileTagCore::verifyFileTagIsExist($fid);
		if (!$res->isSuccess) { return $res; }
		return $res;
	}

	/**
	 * 新增重点标注 - Logic
	 */
	public static function addFileTagLogic($fid, $keyArr) {
		// 获取标注
		// 验证重点标注是否存在
		$res = FileTagCore::verifyFileTagIsExist($fid);
		if (!$res->isSuccess) {
			// 未初始化标注,创建
			// 创建标注
			$res = FileTagCore::createFileTagCore($fid, '[]');
		}
		$tag = $res->data->tag;
		
		// 新增
		$tag = json_decode($tag, true);
		foreach ($keyArr as $key => $val) {
			if (!in_array($val, $tag)) {
				array_push($tag, $val);
			}
		}

		// 更新
		$whereCondt = [
			'fid' => $fid
		];
		$updateData = [
			'tag' => json_encode($tag)
		];
		return FileTagCore::updateFileTagCore($whereCondt, $updateData);
	}

	/**
	 * 删除重点标记 - Logic
	 */
	public static function deleteFileTagLogic($fid, $deleteArr) {
		// 获取标注
		// 验证重点标注是否存在
		$res = FileTagCore::verifyFileTagIsExist($fid);
		if (!$res->isSuccess) {
			// 未初始化标注,创建
			// 创建标注
			$res = FileTagCore::createFileTagCore($fid, '[]');
		}
		$tag = $res->data->tag;

		// 删除
		$tag = json_decode($tag, true);
		if (!empty($deleteArr)) {
			foreach ($deleteArr as $key => $val) {
				if (in_array($val, $tag)) {
					$index = array_search($val, $tag);
					array_splice($tag, $index, 1);
				}
			}
		}

		// 更新
		$whereCondt = [
			'fid' => $fid
		];
		$updateData = [
			'tag' => json_encode($tag)
		];
		$res = FileTagCore::updateFileTagCore($whereCondt, $updateData);

		// 返回最新Tag
		return operationRes(true, 'Delete Successful', ['tag' => $tag]);
	}
}